package com.zhb.cloud.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;

import com.zhb.cloud.curator.utils.CuratorFrameworkUtils;

public class CuratorWatcher {
	/**
	 * PATH
	 */
	private static final String PATH = "/zhb/test";

	public static void main(String[] args) throws Exception {
		// 1.Connect to zk
		CuratorFramework client = CuratorFrameworkUtils.initCuratorFramework();
		System.out.println("zk client start successfully!");

		// 2.Register watcher,if cache data
		PathChildrenCache watcher = new PathChildrenCache(client, PATH, true);
		watcher.getListenable().addListener((client1, event) -> {
			ChildData data = event.getData();
			if (data == null) {
				System.out.println("No data in event[" + event + "]");
			} else {
				System.out.println("Receive event: " + "type=[" + event.getType() + "]" + ", path=[" + data.getPath()
						+ "]" + ", data=[" + new String(data.getData()) + "]" + ", stat=[" + data.getStat() + "]");
			}
		});
		watcher.start(StartMode.BUILD_INITIAL_CACHE);
		System.out.println("Register zk watcher successfully!");
		Thread.sleep(Integer.MAX_VALUE);
	}
}
